
package com.hockeo.tinygds;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;

import com.google.appengine.api.datastore.Key;
import com.hockeo.tinygds.error.TNotLoadableException;

/**
 * Represents a field of type {@link TKey}.
 *
 * @version $Id$
 * @author jjanke
 */
public class TFieldKey extends TField<TKey<?>>
{
  protected TFieldKey( TinyGDSFactory factory, Field field )
  {
    super( factory, field );
  }

  /**
   * Returns the type for which this field which is of Type {@link TKey} is parametrized.
   * This means if the source code says TKey<Car> this method returns a class object
   * representing Car.
   */
  public Class<?> getReferencedType()
  {
    ParameterizedType type = (ParameterizedType) getRealField().getGenericType();

    return (Class<?>) type.getActualTypeArguments()[0];
  }

  @Override
  public Object getValueForDatastore( Object objInstance )
  {
    TKey<?> tkey = super.getValue( objInstance );

    if ( tkey == null )
      return null;

    return getTinyGDSFactory().tKeyToRawKey( tkey );
  }

  @Override
  protected TKey<?> transformDatastoreValue( Object objDatastoreValue )
  {
    if ( objDatastoreValue instanceof Key )
      return getTinyGDSFactory().rawKeyToTKey( (Key) objDatastoreValue, getReferencedType() );

    throw TNotLoadableException.cannotConvertValue( objDatastoreValue, getRealField() );
  }
}
